package com.vision.util.http.util;

import org.apache.http.client.CookieStore;
import org.apache.http.client.protocol.HttpClientContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;

/**
 * @author zhongc
 * @version 1.0
 * @Filename CookieUtil.java
 * <p>
 * Description
 * @Email zhong_ch@foxmail.com
 * @History <li>Author: zhongc</li>
 * <li>Date: 2017/1/19</li>
 * <li>Version: 1.0</li>
 * <li>Content: create</li>
 */
public class CookieUtil {

    private static final Logger logger = LoggerFactory.getLogger(CookieUtil.class);

    /**
     * 反序列化CookiesStore
     *
     * @return
     */
    public static boolean deserializeCookieStore(HttpClientContext httpClientContext, String path) {
        try {
            CookieStore cookieStore = (CookieStore) deserializeMyHttpClient(path);
            httpClientContext.setCookieStore(cookieStore);
        } catch (Exception e) {
            logger.warn("反序列化Cookie失败,没有找到Cookie文件");
            return false;
        }
        return true;
    }

    /**
     * 反序列化对象
     *
     * @param path
     * @throws Exception
     */
    public static Object deserializeMyHttpClient(String path) throws Exception {
        Object object = null;
        try (InputStream fis = new FileInputStream(new File(path)); ObjectInputStream ois = new ObjectInputStream(fis)) {
            object = ois.readObject();
            fis.close();
            ois.close();
            if (object == null) {
                throw new RuntimeException("未获取到数据");
            }
            return object;
        }

    }

    /**
     * 序列化对象
     *
     * @param object
     * @throws Exception
     */
    public static void serializeObject(Object object, String filePath) {
        OutputStream fos = null;
        try {
            fos = new FileOutputStream(filePath);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(object);
            logger.info("序列化成功");
            oos.flush();
            fos.close();
            oos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

